package com.tdcy.framework.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tdcy.framework.bean.PageInfo;

/**
 * web辅助类.
 */
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public abstract class WebUtils {
	private static Logger log = LoggerFactory.getLogger(WebUtils.class);

	private WebUtils() {

	}

	public static String getBasePath(HttpServletRequest request) {
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
		return basePath;
	}

	public static boolean isAjax(HttpServletRequest request) {
		return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
	}

	/**
	 * 检查请求对象是否为AJAX.
	 * 
	 * @param request
	 *            请求对象
	 * @return true, if is aJAX request
	 */
	public static boolean isEasyUIRequest(final HttpServletRequest request) {
		if (request == null) {
			return false;
		}

		String pageno = request.getParameter("page");

		if (StringUtils.isEmpty(pageno)) {
			return false;
		}

		return true;
	}

	/**
	 * 获取Text的内容类型.
	 * 
	 * @return the text content type
	 */
	public static String getTextContentType() {
		return "text/plain; charset=utf-8";
	}

	/**
	 * 获取HTML的内容类型.
	 * 
	 * @return the text content type
	 */
	public static String getHtmlContentType() {
		return "text/html; charset=utf-8";
	}

	/**
	 * 检查请求对象是否为POST.
	 * 
	 * @param request
	 *            请求对象
	 * @return true, if is POST request
	 */
	public static boolean isPostRequest(final HttpServletRequest request) {
		return "POST".equals(request.getMethod());
	}

	/**
	 * 检查请求对象是否为GET.
	 * 
	 * @param request
	 *            请求对象
	 * @return true, if is GET request
	 */
	public static boolean isGetRequest(final HttpServletRequest request) {
		return "GET".equals(request.getMethod());
	}

	/**
	 * 输出JSON错误信息.
	 * 
	 * @param response
	 *            响应对象
	 * @param message
	 *            错误信息
	 * @param t
	 *            异常对象
	 */
	public static Map createJSONError(final Throwable t) {
		return createJSONError(null, t);
	}

	/**
	 * 输出JSON错误信息.
	 * 
	 * @param response
	 *            响应对象
	 * @param message
	 *            错误信息
	 * @param t
	 *            异常对象
	 */
	public static Map createJSONError(final String message) {
		return createJSONError(message, null);
	}

	/**
	 * 输出JSON错误信息.
	 * 
	 * @param response
	 *            响应对象
	 * @param message
	 *            错误信息
	 * @param t
	 *            异常对象
	 */
	public static Map createJSONError(final String message, final Throwable t) {
		Map map = new HashMap();
		map.put("errortype", t == null ? "1" : "2");
		if (StringUtils.isEmpty(message)) {
			map.put("message", t == null ? "" : t.getMessage());
		} else {
			map.put("message", message);
		}

		map.put("data", null);

		return map;
	}

	/**
	 * 输出JSON返回值.
	 * 
	 * @param response
	 *            响应对象
	 * @param message
	 *            提示信息
	 * @param value
	 *            参数对象
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public static Map createJSONSuccess(final String message) {
		return createJSONSuccess(message, null);
	}

	/**
	 * 输出JSON返回值.
	 * 
	 * @param response
	 *            响应对象
	 * @param message
	 *            提示信息
	 * @param value
	 *            参数对象
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public static Map createJSONSuccess(final String message, final Object value) {
		Map map = new HashMap();
		map.put("errortype", "0");
		map.put("message", message);
		map.put("data", value);

		return map;
	}

	public static void writeReponse(HttpServletResponse response, final String message) {
		try {
			response.setContentType("text/html");
			response.getWriter().write(message);
			response.getWriter().flush();
		} catch (IOException e) {
			log.error("对异常进行JSON转换时出错", e);
			e.printStackTrace();
		}
	}

	/**
	 * 获取请求资源路径（包含参数）.
	 * 
	 * @param request
	 *            请求对象
	 * @return URI
	 */
	public static String getRequestResource(final HttpServletRequest request) {
		StringBuffer sb = new StringBuffer(512);
		sb.append(request.getServletPath());
		String queryString = request.getQueryString();
		if (StringUtils.hasLength(queryString)) {
			sb.append("?");
			sb.append(queryString);
		}

		return sb.toString();
	}

	/**
	 * 获取cookie.
	 * 
	 * @param request
	 *            the request
	 * @param name
	 *            the name
	 * @return the cookie
	 */
	public static Cookie getCookie(final HttpServletRequest request, final String name) {
		Cookie cookies[] = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (name.equalsIgnoreCase(cookies[i].getName())) {
					return cookies[i];
				}
			}
		}
		return null;
	}

	/**
	 * 获取客户端地址.
	 * 
	 * @param request
	 *            the request
	 * @return 客户端地址
	 */
	public static String getClientIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip.equals("0:0:0:0:0:0:0:1")) {// 况只有在服务器和客户端都在同一台电脑上才会出现
			ip = "127.0.0.1";
		}
		return ip;
	}

	/**
	 * 输出JSON返回值.
	 * 
	 * @param response
	 *            响应对象
	 * @param message
	 *            提示信息
	 * @param value
	 *            参数对象
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public static Map createLayTableSuccess(final String message, PageInfo page) {
		Map map = new HashMap();
		map.put("code", 0);
		map.put("msg", message);
		map.put("count", page.getTotalRecord());
		map.put("data", page.getResultsList());

		return map;
	}

	public static Map createLayTableSuccess(final String message, int count, List dataList) {
		Map map = new HashMap();
		map.put("code", 0);
		map.put("msg", message);
		map.put("count", count);
		map.put("data", dataList);

		return map;
	}

	public static Map createLayTableError(final String message) {
		Map map = new HashMap();
		map.put("code", 1);
		map.put("message", message);
		map.put("count", 0);
		map.put("data", "");

		return map;
	}
}
